// 发布服务：处理词条打包和CDN上传

/**
 * 生成翻译包 (多语言JSON对象)
 */
async function generateTranslationBundle(product, translations) {
  const bundles = {};
  
  product.supportedLocales.forEach(locale => {
    bundles[locale] = {};
    
    translations.forEach(translation => {
      const key = translation.namespace !== 'common' 
        ? `${translation.namespace}.${translation.key}` 
        : translation.key;
      
      const value = translation.locales?.get(locale) 
        || translation.locales?.get(product.defaultLocale) 
        || '';
      
      // 支持嵌套键结构 (如: nav.home -> { nav: { home: '...' } })
      const keys = key.split('.');
      let current = bundles[locale];
      
      for (let i = 0; i < keys.length - 1; i++) {
        if (!current[keys[i]]) {
          current[keys[i]] = {};
        }
        current = current[keys[i]];
      }
      current[keys[keys.length - 1]] = value;
    });
  });
  
  return bundles;
}

/**
 * 上传到CDN
 * 实际项目中应该调用真实的CDN API (如阿里云OSS、AWS S3等)
 */
async function uploadToCDN(productCode, version, locale, bundle) {
  // 模拟上传过程
  // 实际应该：
  // 1. 将 bundle 序列化为 JSON
  // 2. 调用 CDN SDK 上传文件
  // 3. 返回 CDN URL
  
  const jsonContent = JSON.stringify(bundle, null, 2);
  const fileName = `${productCode}/${version}/${locale}.json`;
  
  // 模拟CDN URL
  const cdnBaseUrl = process.env.CDN_BASE_URL || 'https://cdn.example.com/i18n';
  const cdnUrl = `${cdnBaseUrl}/${fileName}`;
  
  // TODO: 实际调用CDN API上传
  // await cdnClient.put(fileName, jsonContent, { contentType: 'application/json' });
  
  console.log(`[模拟] 上传到CDN: ${cdnUrl}`);
  
  return cdnUrl;
}

module.exports = {
  generateTranslationBundle,
  uploadToCDN
};

